package com.itstherules.jmsunit.header;

import java.util.Map;

import javax.jms.JMSException;
import javax.jms.TextMessage;

import com.itstherules.jmsunit.headers.JmsHeadersDefinition;
import com.itstherules.jmsunit.managers.QueueManager;

public class HeadersPopulator {
	private final QueueManager manager;

	public HeadersPopulator(QueueManager manager) {
		this.manager = manager;
	}
	
	public void populate(JmsHeadersDefinition definition, TextMessage textMessage) {
		Map<String, String> headers = definition.getHeaders();

		for (String key : headers.keySet()) {
			try {
				if ( !setJMSHeader(textMessage, key, headers.get(key))) {
					textMessage.setStringProperty(key, headers.get(key));
				}
			} catch (JMSException e) {
				throw new RuntimeException("Programmatic error: " + e);
			}
		}
	}

	private boolean setJMSHeader(TextMessage textMessage, final String key, final String value) throws JMSException {
		if (key.equals("JMSReplyTo")) {
			textMessage.setJMSReplyTo(manager.createQueue(value));
			return true;
		} else if (key.equals("JMSCorrelationID")) {
			textMessage.setJMSCorrelationID(value);
			return true;
		}  else if (key.equals("JMSMessageID")) {
			textMessage.setJMSMessageID(value);
			return true;
		} else if (key.equals("JMSType")) {
			textMessage.setJMSType(value);
			return true;
		} else if (key.equals("JMSDestination")) {
			textMessage.setJMSDestination(manager.createQueue(value));
			return true;
		}
		return false;
	}

}
